/// <reference path="../_all.ts" />

module Application.Controllers {

    export class MembersController implements Application.Interfaces.Controllers.IController {

        _server_id: number;
        _timeout_id: any;
        _timeout_delay: number;

        public static $inject = [
            '$rootScope',
            '$scope',
            '$location',
            '$routeParams',
            '$timeout',
            'MemberService',
            'ServerService',
            'TranslationService',
        ];

        membersResult: {
            (data): void;
            (data, err): void;
        };

        membershipsResult: {
            (data): void;
            (data, err): void;
        };

        serverResult: {
            (data): void;
            (data, err): void;
        };

        constructor(public RootScope: Application.Interfaces.Scopes.IRootScope,
            public Scope: Application.Interfaces.Scopes.IMembersScope,
            public Location: ng.ILocationService,
            public RouteParams: Application.Interfaces.Routing.IServerRouteParams,
            public TimeOut: ng.ITimeoutService,
            public Members: Application.Interfaces.Services.IMemberService,
            public Server: Application.Interfaces.Services.IServerService,
            public Translations: Application.Interfaces.Services.ITranslationService) {

                this.Scope.vm = this;
                this.Scope.user = this.RootScope.user;
                this.Scope.location = this.Location;
                this.Scope.messages = new Application.Utility.Messages();
                this.Scope.navigations = new Application.Utility.Navigations();
                this.Scope.server = <Application.Resources.IServer>{};
                this.Scope.members = <Application.Resources.IMember[]>[];

                this._server_id = 0;
                if (this.RouteParams.server_id) {
                    this._server_id = parseInt(this.RouteParams.server_id.toString());
                };

                this.Scope.navigations.AddLink(Translations.Translate("SERVERLIST"), "/servers", false, false, Application.Constants.Icons.Servers);

                if (this._server_id > 0) {
                    this.Scope.navigations.AddLink(Translations.Translate("SERVER"), "/server/" + this._server_id, false, false, Application.Constants.Icons.Server);
                    this.Scope.navigations.AddLink(Translations.Translate("SERVERACTIONS"), "/actions/" + this._server_id, false, true, Application.Constants.Icons.Actions);
                    this.Scope.navigations.AddLink(Translations.Translate("SERVERRIGHTS"), "/members/" + this._server_id, true, true, Application.Constants.Icons.Rights);
                } else {
                    this.Scope.navigations.AddLink(Translations.Translate("ACTIONS"), "/actions", false, false, Application.Constants.Icons.Actions);
                };
                if (this.Scope.user && this.Scope.user.role && this.Scope.user.role >= 2) {
                    this.Scope.navigations.AddLink(Translations.Translate("PLAYERS"), "/players", false, false, Application.Constants.Icons.Bans);
                };
                if (this.Scope.user && this.Scope.user.role && this.Scope.user.role >= 8) {
                    this.Scope.navigations.AddLink(Translations.Translate("USERS"), "/users", false, false, Application.Constants.Icons.Users);
                };
                this.Scope.navigations.AddLinkRight(Translations.Translate("ACCOUNT"), "/users/" + this.Scope.user.user_id, false);
                this.Scope.navigations.AddLinkRight(Translations.Translate("LOGOUT"), "/", false);

                if (this._server_id > 0) {
                    this.membersResult = (data, err?) => {
                        this.membersResultProxy.apply(this, [data, err]);
                    }

                    this.membershipsResult = (data, err?) => {
                        this.membershipsResultProxy.apply(this, [data, err]);
                    }

                    this.serverResult = (data, err?) => {
                        this.serverResultProxy.apply(this, [data, err]);
                    };

                    this.getServer();
                };
        }

        public log(msg: string) {
            //console.log(msg);
        }

        public refresh() {
            if (this.Scope.server != null && this._server_id && this._server_id > 0) {
                this.getMembers();
            };
        }

        public getMembers() {
            this.log('getMembers');
            if (this.Scope.server != null && this._server_id && this._server_id > 0) {
                this.Members.UpdateMemberShips(this.membershipsResult);
            };
        }

        private membershipsResultProxy(data, err) {
            this.log('memberships result');
            if (data != null) {
                this.Members.GetMembers(this.membersResult);
            } else {
                if (err != null) {
                    this.Scope.messages.AddAndGrowl(Application.Utility.MessageType.error, err.data.status + ' ' + err.data.type, err.data.message);
                } else {
                    this.Scope.messages.AddAndGrowl(Application.Utility.MessageType.error, '000 Unknown', this.Translations.Translate('UNKNOWNERROR'));
                };
            };
        }

        private ensureServerRights(member: Application.Resources.IMember) {
            if (!member.rights) {
                member.rights = <Application.Resources.IMemberRights[]>[];
            };
            var found = false;
            for (var i = 0; i < member.rights.length; i++) {
                if (member.rights[i] != null && member.rights[i].server_id == this._server_id) {
                    found = true;
                    break;
                };
            };
            if (!found) {
                var rights = <Application.Resources.IMemberRights>{};
                rights.server_id = this._server_id;
                rights.member_id = member.member_id;
                rights.rights_list = "";
                member.rights.push(rights);
            };
        }

        private membersResultProxy(data, err) {
            this.log('members result');
            if (data != null) {
                var members = <Application.Resources.IMember[]> data;
                if (members != null && members.length > 0) {
                    this.Scope.messages.AddAndGrowl(Application.Utility.MessageType.success, "Info", new Application.Utility.String(this.Translations.Translate('MEMBERSFOUND')).format(members.length.toString()));
                    var result: Application.Resources.IMember;
                    for (var i = 0; i < this.Scope.members.length; i++) {
                        result = null;
                        for (var j = 0; j < members.length; j++) {
                            if (this.Scope.members[i].member_id == members[j].member_id) {
                                result = members[j];
                                this.ensureServerRights(result);
                                members.splice(j, 1);
                                break;
                            };
                        };
                        if (result == null) {
                            this.Scope.members.splice(i, 1);
                            i--;
                        } else {
                            this.Scope.members[i] = result;
                        };
                    }; 
                    for (var i = 0; i < members.length; i++) {
                        result = members[i];
                        this.ensureServerRights(result);
                        this.Scope.members.push(result);
                    };
                    this.Scope.membersListForm.$setPristine();
                } else {
                    this.Scope.messages.AddAndGrowl(Application.Utility.MessageType.error, "Error", this.Translations.Translate('NOMEMBERSFOUND'));
                };
            } else {
                if (err != null) {
                    this.Scope.messages.AddAndGrowl(Application.Utility.MessageType.error, err.data.status + ' ' + err.data.type, err.data.message);
                } else {
                    this.Scope.messages.AddAndGrowl(Application.Utility.MessageType.error, '000 Unknown', this.Translations.Translate('UNKNOWNERROR'));
                };
            };
        }

        public getServer() {
            if (this._server_id != null) {
                this.log('getServer: ' + this._server_id);
                this.Server.GetServer(this._server_id, this.serverResult);
            } else {
                this.Scope.messages.AddAndGrowl(Application.Utility.MessageType.error, "Error", this.Translations.Translate('NOSERVERID'));
            };
        }

        private serverResultProxy(data, err) {
            this.log('server result');
            if (data != null) {
                var server = <Application.Resources.IServer> data;
                if (server != null) {
                    Application.Resources.ServerUtility.fixBooleans(server);
                    this.Scope.server = server;
                    this.Scope.messages.AddAndGrowl(Application.Utility.MessageType.info, "Status", this.Translations.Translate('SERVERINFOLOADED'));
                    this.getMembers();
                } else {
                    this.Scope.messages.AddAndGrowl(Application.Utility.MessageType.error, "Error", this.Translations.Translate('SERVERNOTFOUND'));
                };
            } else {
                if (err != null) {
                    this.Scope.messages.AddAndGrowl(Application.Utility.MessageType.error, err.data.status + ' ' + err.data.type, err.data.message);
                } else {
                    this.Scope.messages.AddAndGrowl(Application.Utility.MessageType.error, '000 Unknown', this.Translations.Translate('UNKNOWNERROR'));
                };
            };
        }

        public deleteMember(member: Application.Resources.IMember) {

        }

        public saveRights() {
            if (this._server_id != null) {
                if (this.Scope.members.length > 0) {
                    this.log('saveRights: ' + this._server_id);
                    this.Members.SaveMemberRights(this._server_id, this.Scope.members, this.membersResult);
                };
            } else {
                this.Scope.messages.AddAndGrowl(Application.Utility.MessageType.error, "Error", this.Translations.Translate('NOSERVERID'));
            };
        }
    };
}